<template>
    <div class="main" @scroll.passive="scrollTop($event)">
        <!-- 优惠卷头部 -->
        <div class="coupon-top">
            <el-space wrap :size="10">
                <el-input v-model="searchData.couponName" placeholder="请输入优惠卷名称" clearable
                    @keyup.enter.native="handlrsearch" />
                <el-select v-model="searchData.couponType" placeholder="请选择优惠卷类型" style="width: 10vw;" clearable
                    @clear="searchData.couponType=undefined">
                    <el-option label="满减卷" :value="1">满减卷</el-option>
                    <el-option label="立减卷" :value="2">立减卷</el-option>
                    <el-option label="全部" value="">全部</el-option>
                </el-select>
                <el-select v-model="searchData.couponStatus" placeholder="请选择优惠卷状态" style="width: 10vw;" clearable
                    @clear="searchData.couponStatus=undefined">
                    <el-option label="下架" :value="0">下架</el-option>
                    <el-option label="正常" :value="1">正常</el-option>
                    <el-option label="已过期" :value="-1">已过期</el-option>
                    <el-option label="全部" value="">全部</el-option>
                </el-select>
                <el-button type="primary" :icon="Search" @click="handlrsearch">查找</el-button>
                <el-button type="primary" :icon="Plus" @click="handlrAdd">添加</el-button>
                <el-button type="primary" :icon="Download" @click="deriveExcel">当前页导出</el-button>
            </el-space>
        </div>
        <!-- 优惠卷列表 -->
        <div class="coupon-table">
            <div>
                <el-table :data="tableData" border style="width: 100%;" id="table">
                    <el-table-column prop="id" label="优惠卷ID" align="center" sortable width="110" />
                    <el-table-column prop="title" label="优惠卷名称" align="center" width="110" />
                    <el-table-column prop="type" label="优惠卷类型" align="center" width="110">
                        <template #default="scope">
                            <span>{{scope.row.type==1?'满减卷':'立减卷'}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="description" label="介绍" align="center" width="110" />
                    <el-table-column prop="total" label="优惠卷数量" align="center" width="110" />
                    <el-table-column prop="surplus" label="剩余数量" align="center" width="90" />
                    <el-table-column prop="limit" label="每人限额" align="center" width="90" />
                    <el-table-column prop="discount" label="满减金额" align="center" width="90">
                        <template #default="scope">
                            <span>减免{{scope.row.discount}}元</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="min" label="最低消费" align="center" width="90">
                        <template #default="scope">
                            <span>满{{scope.row.min}}元可用</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="status" label="状态" align="center" width="80">
                        <template #default="scope">
                            <template v-if="scope.row.gmtEnd<new Date().getTime()">
                                <el-tag type="danger">已过期</el-tag>
                            </template>
                            <template v-else>
                                <el-tag :type="scope.row.status==0?'danger':''">{{scope.row.status==0?'下架':'正常'}}
                                </el-tag>
                            </template>
                        </template>
                    </el-table-column>
                    <el-table-column prop="categoryTitle" label="使用类目名称" align="center" width="110">
                        <template #default="scope">
                            <el-tag>{{scope.row.categoryTitle?scope.row.categoryTitle:'全部类目'}}</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="categoryId" label="使用类目ID" align="center" width="110" />
                    <el-table-column prop="days" label="领卷相对天数" align="center" width="110">
                        <template #default="scope">
                            <span>{{scope.row.days?scope.row.days:'无'}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="gmtStart" label="领卷开始时间" align="center" width="200">
                        <template #default="scope">
                            <template v-if="scope.row.gmtStart">
                                {{new Date(scope.row.gmtStart).formate('yyyy-MM-dd hh:mm:ss')}}
                            </template>
                            <template v-else>
                                <span>无</span>
                            </template>
                        </template>
                    </el-table-column>
                    <el-table-column prop="gmtEnd" label="领卷结束时间" align="center" width="200">
                        <template #default="scope">
                            <template v-if="scope.row.gmtEnd">
                                {{new Date(scope.row.gmtEnd).formate('yyyy-MM-dd hh:mm')}}
                            </template>
                            <template v-else>
                                <span>无</span>
                            </template>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" align="center" width="200">
                        <template #default="scope">
                            <el-button v-if="scope.row.gmtEnd<new Date().getTime()" type="primary">已过期</el-button>
                            <el-button :type="scope.row.status==0?'primary':'danger'" v-else
                                @click="handlrChangeStatus(scope.row)">{{scope.row.status==0?'激活':'冻结'}}</el-button>
                            <el-button type="info" @click="handlrSee(scope.row)">查看</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div>
                <!-- Dialog 对话框default -->
                <el-dialog v-model="dialogFormVisible" :title="title?'创建':'编辑'" :destroy-on-close="true" style="width: 39%;">
                    <el-form ref="ruleFormRef" :model="modelfy" require-asterisk-position="left" label-width="120px"
                        :rules="rules" class="demo-ruleForm" status-icon :disabled="title?false:true">
                        <el-form-item label="优惠卷名称" prop="title" class="is-required">
                            <el-input v-model.trim="modelfy.title" clearable />
                        </el-form-item>
                        <el-form-item label="优惠卷类型" prop="type" class="is-required">
                            <el-select v-model="modelfy.type" clearable placeholder="请输入优惠价类型">
                                <el-option label="满减卷" :value="1">满减卷</el-option>
                                <el-option label="立减卷" :value="2">立减卷</el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="介绍" prop="description" class="is-required">
                            <el-input v-model.trim="modelfy.description" clearable />
                        </el-form-item>
                        <el-form-item label="优惠卷数量" prop="total" class="is-required">
                            <el-input v-model="modelfy.total">
                                <template #append>张</template>
                            </el-input>
                        </el-form-item>
                        <el-form-item label="每人限制" prop="limit" class="is-required">
                            <el-input v-model="modelfy.limit">
                                <template #append>张</template>
                            </el-input>
                        </el-form-item>
                        <el-form-item label="优惠金额" prop="discount" class="is-required">
                            <el-input v-model="modelfy.discount">
                                <template #append>元</template>
                            </el-input>
                        </el-form-item>
                        <el-form-item label="最低消费" prop="min" class="is-required">
                            <el-input v-model="modelfy.min">
                                <template #append>元</template>
                            </el-input>
                        </el-form-item>
                        <el-form-item label="优惠卷状态" prop="status" class="is-required">
                            <el-select v-model="modelfy.status" clearable placeholder="请输入用户等级">
                                <el-option label="下架" :value="0">下架</el-option>
                                <el-option label="正常" :value="1">正常</el-option>
                                <el-option label="已过期" :value="-1">已过期</el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="有效期">
                            <el-radio-group v-model="expiration">
                                <el-radio-button :label="0">领卷相对天数</el-radio-button>
                                <el-radio-button :label="1">指定绝对时间</el-radio-button>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="" v-if="expiration==0">
                            <el-input v-model="modelfy.days">
                                <template #append>天</template>
                            </el-input>
                        </el-form-item>
                        <el-form-item label="" v-else>
                            <el-date-picker v-model="modelfy.gmtStart" type="datetime" placeholder="开始时间"
                                format="YYYY/MM/DD HH:mm:ss" value-format="x" />
                            <span>至</span>
                            <el-date-picker v-model="modelfy.gmtEnd" type="datetime" placeholder="结束时间"
                                format="YYYY/MM/DD HH:mm:ss" value-format="x" />
                        </el-form-item>
                        <el-form-item label="商品限制范围">
                            <el-radio-group v-model="limitedField">
                                <el-radio-button :label="0" >全场通用</el-radio-button>
                                <el-radio-button :label="1" >指定分类</el-radio-button>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="优惠类目" v-if="limitedField==1">
                            <div class="example-block">
                                <el-cascader :options="options"  :props="props1" clearable v-model="modelfy.categoryId"/>
                            </div>
                        </el-form-item>
                    </el-form>
                    <template #footer>
                        <span class="dialog-footer">
                            <el-button @click="dialogFormVisible=false">取消</el-button>
                            <el-button type="primary" @click="submitForm(ruleFormRef)" v-if="title">确定</el-button>
                        </span>
                    </template>
                </el-dialog>
            </div>
        </div>
        <!-- 分页组件 -->
        <div>
            <Paging v-bind="pagingDatas" @page-change="pageChange" ></Paging>
        </div>
        <el-backtop :right="100" :bottom="100" ref="main" target=".main" :visibility-height="0" v-if="bool" />
    </div>
</template>
<script  setup lang="ts">
import { nextTick, reactive, ref, watch } from 'vue'
import { Search, Plus, Download } from '@element-plus/icons-vue'
import { ClassPagination } from "#/index";
import { ElMessage } from 'element-plus'
import type { FormInstance } from 'element-plus'
import  deriveExcel  from "@/utils/export";
import Paging from "@/components/paging/Paging.vue";
import { get } from "@/utils/request";
import "@/utils/dataFriend"
const ruleFormRef = ref<FormInstance>()
let main = ref()  //滚动组件对象的引用
let rollHeight = ref(0)  //滚动距离
let bool = ref(true)  //用来判断滚动组件的显示隐藏
let tableData: TypeCoupon[] = reactive([]) //优惠卷列表
let dialogFormVisible = ref(false) //控制修改框是否可见
let expiration = ref(0) 
let limitedField = ref(0)
let title = ref(true)
const props1 = {
  checkStrictly: true,
  value:'id',
  label:"title",
  children:"childrenList"
}
const options:TypeOptions[] = reactive([])//类目列表
let modelfy = reactive({
    title: "", //优惠卷名称
    type: "", //优惠卷类型
    description: "", //介绍
    total: 0, //优惠卷数量
    limit: 0, //每人限领
    discount: 0, //优惠金额
    min: 0, //最低消费
    status: 1, //优惠卷状态
    days: "", //领卷相对天数
    gmtStart: "", //开始时间
    gmtEnd: "", //结束时间
    categoryId:''//优惠类目
})
//分页数据
let pagingDatas = reactive(new ClassPagination())
//查找数据
const searchData = reactive({
    couponName: '', //优惠卷名称
    couponStatus: undefined,//优惠卷状态
    couponType: undefined,//优惠卷类型
})
let newsearchData = { ...searchData }
//加载优惠卷列表
function loadCouponList() {
    let data = {
        _gp: 'admin.coupon',
        _mt: 'list',
        title: newsearchData.couponName,
        type: newsearchData.couponType,
        status: newsearchData.couponStatus,
        pageNo: pagingDatas.page,
        limit: pagingDatas.limit
    }
    get(data).then((res) => {
        console.log(res)
        if (200 == res.errno) {
            tableData.length = 0
            tableData.push(...res.data.items)
            pagingDatas.total = res.data.total
        }else{
            ElMessage.error(res.errmsg)
        }
    })
}
//用户名验证
const validateTitle = (rule: object, value: string, callback: Function) => {
    if ('' === value) {
        return callback(new Error('优惠卷名称不能为空'))
    } else {
        callback()
    }
}
//优惠卷数量验证
const validatTotal = (rule: object, value: string, callback: Function) => { 
    let regexp = /^\d{1,}$/   
    if ('' === value) {
        return callback(new Error('不能为空'))
    } else if(!regexp.test(value)){
        return callback(new Error('请输入数字'))
    }else if(modelfy.limit>modelfy.total) {
        return callback(new Error('每人限领数量不能大于优惠卷数量'))
    }
    callback()
}
//每人限领
const validatDiscount = (rule: object, value: string, callback: Function) => { 
    let regexp = /^\d{1,}$/   
    if ('' === value) {
        return callback(new Error('不能为空'))
    } else if(!regexp.test(value)){
        return callback(new Error('请输入数字'))
    }else{
        callback()
    }
}
//优惠金额
const validatLimit = (rule: object, value: string, callback: Function) => { 
    let regexp = /^\d{1,}$/   
    if ('' === value) {
        return callback(new Error('不能为空'))
    } else if(!regexp.test(value)){
        return callback(new Error('最多领99张'))
    }else{
        callback()
    }
}

//最低消费
const validatMin = (rule: object, value: string, callback: Function) => { 
    let regexp = /^\d{1,}$/   
    if ('' === value) {
        return callback(new Error('不能为空'))
    } else if(!regexp.test(value)){
        return callback(new Error('请输入数字'))
    }else if(modelfy.discount>modelfy.min){
        return callback(new Error('最低消费金额不能小于优惠卷金额'))
    }
   callback()  
}
//类目列表
function lodeCategory() {
   if(options.length==0){
    let data = {
        _gp:'admin.category',
        _mt:'categoryTree',
    }
    get(data).then((res)=>{
        console.log(res)
        if(200==res.errno){
            options.length = 0
            options.push(...res.data)
        }else{
          ElMessage.error(res.errmsg)
        }
    })
   }
}
lodeCategory()

//查看
function handlrSee(row:TypeCoupon) {
    title.value = false
    Object.assign(modelfy,newModelfy)
    Object.assign(modelfy,row)
    console.log(row)
    expiration.value = row.gmtStart?1:0
    limitedField.value = row.categoryTitle ? 1:0
    if(row.gmtEnd<new Date().getTime()){
        modelfy.status = -1
    }
    dialogFormVisible.value=true
}

//失焦触发验证
const rules = reactive({
    title: [{ validator: validateTitle, trigger: 'blur' }],
    total:[{ validator: validatTotal, trigger: 'blur' }],
    limit:[{ validator: validatLimit, trigger: 'blur' }],
    discount:[{ validator: validatDiscount, trigger: 'blur' }],
    min:[{ validator: validatMin, trigger: 'blur' }]
})
//更改状态
function handlrChangeStatus(row: TypeCoupon) {
    if (row.status == 1) {
        if (row.gmtEnd < new Date().getTime()) {
            row.status = 1
        } else {
            row.status = 0
        }
    } else {
        row.status = 1
    }
    let data = {
        _gp: 'admin.coupon',
        _mt: 'updateCouponStatus',
        id: row.id,
        status: row.status
    }
    get(data).then((res) => {
        ElMessage.success("修改成功")
        loadCouponList()
    })
}

//查找
function handlrsearch() {
    Object.assign(newsearchData, searchData)
    loadCouponList()
}
let newModelfy = {...modelfy} 
//添加
function handlrAdd() {
    dialogFormVisible.value = true
    Object.assign(modelfy,newModelfy)
    expiration.value = 0
    title.value = true
}


//添加确定
function submitForm(formEl: FormInstance | undefined) {
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
            let value = modelfy.categoryId.length-1
            let data = {
                _gp:'admin.coupon',
                _mt:'create',
                title:modelfy.title,
                type:modelfy.type,
                description:modelfy.description,
                total:modelfy.total,
                limit:modelfy.limit,
                discount:modelfy.discount,
                min:modelfy.min,
                status:modelfy.status,
                categoryId:modelfy.categoryId[value],
                days:modelfy.days,
                gmtStart:modelfy.gmtStart,
                gmtEnd:modelfy.gmtEnd
            }
            get(data).then((res)=>{
                if(200==res.errno){
                    dialogFormVisible.value = false
                    ElMessage.success("添加成功")
                    loadCouponList()
                }else{
                    ElMessage.error(res.errmsg)
                }
            })
        } else {
            console.log('error submit!')
            ElMessage.error("新增失败")
            return false
        }
    })
}
//分页组件每次调用事件
function pageChange(e: TypePaGing) {
    pagingDatas.page = e._page
    pagingDatas.limit = e._limit
    loadCouponList()
    nextTick(() => {
        main.value.$el.click?.()
    })
}
//滚动事件
let scrollTop = (e: Event) => {
    rollHeight.value = Math.floor((e.target as EventTarget).scrollTop)
}
//监听滚动的距离
watch(rollHeight, (val: number) => {
    //    console.log(val);
    bool.value = val > 60
})

loadCouponList()
</script>
<style scoped lang="less">
.coupon-top {
    margin: 15px 0px;

    .el-input {
        width: 11vw;
    }
}
</style>